package cn.wolfcode.wolf2world.web.interceptor;

import cn.wolfcode.wolf2world.domain.UserInfo;
import cn.wolfcode.wolf2world.redis.service.UserRedisService;
import cn.wolfcode.wolf2world.vo.JsonResult;
import cn.wolfcode.wolf2world.web.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录拦截器
 * @author 杨兴健
 * @Date 2020/8/9 18:54
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserRedisService userRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头的token
        String token = request.getHeader("token");
        //判断token是否存在redis数据库中
        UserInfo user = userRedisService.getCurrentUser(token);
        if (Objects.nonNull(user)) {
            return true;
        }
        //判断是否非跨域的动态请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判断访问的方法是否要做登录拦截
        if (((HandlerMethod) handler).hasMethodAnnotation(RequiredLogin.class)) {
            response.getWriter().println(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }
        return true;
    }
}
